package aom.ju.ss.view.shua

import android.os.Message
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import aom.ju.ss.R
import aom.ju.ss.databinding.VideoFragmentBinding
import aom.ju.ss.databinding.VideoItemBinding
import aom.ju.ss.lpInterface.MyHttpCallBack
import aom.ju.ss.mode.*
import aom.ju.ss.utils.*
import aom.ju.ss.utils.http.LP_API
import aom.ju.ss.utils.http.OKHttpUtils
import aom.ju.ss.view.base.BaseFragment
import aom.ju.ss.view.base.jzvd.JYVideoPlayer
import aom.ju.ss.view.base.ListHolder
import aom.ju.ss.view.base.PAdapter
import aom.ju.ss.view.base.jzvd.Jzvd
import aom.ju.ss.view.base.jzvd.JzvdStd
import aom.ju.ss.view.dialog.CommentDialog
import aom.ju.ss.view.dialog.NavigationPopup
import aom.ju.ss.view.dialog.SharePromotionDialogLp
import aom.ju.ss.view.main.MainActivity
import com.bumptech.glide.Glide
import com.google.gson.Gson

/**
 * 刷店->推荐
 */
class VideoFragment : BaseFragment() {
    lateinit var binding: VideoFragmentBinding
    private lateinit var pAdapter: PAdapter
    private var videoList = arrayListOf<VideoListData>()
    lateinit var layoutManager: LinearLayoutManager
    private lateinit var snapHelper: PagerSnapHelper
    private var isLoading = false
    private var videoPlayer: JYVideoPlayer? = null

    companion object {
        var page = 1
        var category_id = ""
        fun getMys(): VideoFragment {
            return VideoFragment()
        }

        var my: VideoFragment? = null
    }


    override fun init() {
        my = this
        binding = viewBinding as VideoFragmentBinding

        layoutManager = LinearLayoutManager(activity)
        SendMsg.sendEvent(LpKey.TO_LOCATE)
        binding.small.setOnRefreshListener {
            page = 1
            getData()
        }
        pAdapter = PAdapter(
            videoList, R.layout.video_item
        ) { bb, position ->
            val ib = bb as VideoItemBinding
            val info = videoList[position]
            ib.info = info
            ib.jinxaun.info = info
            if (position == 0 && videoPlayer == null) {
                videoPlayer = ib.jyVideo
            }
            val url = videoList[position].video_url
            ib.jyVideo.setUp(url, "", JzvdStd.STATE_PREPARING)
            if (position == 0) {
                if (MainActivity.mCurrentPosition == 0 && HomeShuaFragment.my?.binding?.virePager?.currentItem == 2) {
                    ib.jyVideo.startVideo()
                }
            }
            Glide.with(this)
                .load(videoList[position].video_url + "?vframe/jpg/offset/0/")
                .into(ib.jyVideo.thumbImageView)

            ib.jyVideo.mRetryBtn.setOnClickListener {
                ib.jyVideo.setUp(url, "", JzvdStd.STATE_PREPARING)
                ib.jyVideo.startVideo()
            }
            ib.dianzan.setOnClickListener {
                OKHttpUtils(activity, false)
                    .SetApiUrl(LP_API.video_like)
                    .SetKey("id")
                    .SetValue(info.id.toString())
                    .POST(object : MyHttpCallBack {
                        override fun ok(jsonString: String?, httpTY: String?) {
                            val mode = Gson().fromJson(jsonString, PublicMode::class.java)
                            if (mode.msg == "点赞成功") {
                                "点赞成功".show()
                                info.is_like = 1
                                info.like_num++
                            } else {
                                info.is_like = 0
                                info.like_num--
                            }
                            videoList[position] = info
                            ib.info = info
                        }

                        override fun error(e: String?, jsonString: String?, httpTY: String?) {
                            e?.show
                        }


                    })
            }
            ib.name.setOnClickListener {

            }
            //分享
            ib.fx.setOnClickListener {
                SharePromotionDialogLp(info.id, activity) {
                    info.share_num++
                    videoList[position] = info
                    ib.info = info
                }

            }

            //评论
            ib.pl.setOnClickListener {
                CommentDialog(activity, info.id.toString(), object : CommentDialog.CommentCallback {
                    override fun commentCallback() {
                        videoList[position].comment_num++
                        ib.info = videoList[position]
                    }
                })
            }
            // 导航
            ib.addTc.setOnClickListener {
                if (info.shop?.lat != null && info.shop?.lat!!.length > 5 && info.shop?.lng != null && info.shop?.lng!!.length > 5) {
                    NavigationPopup(activity, info.shop?.lat, info.shop?.lng)
                }
            }
            ib.name.setOnClickListener { ib.addTc.performClick() }
            ib.juli.setOnClickListener { ib.addTc.performClick() }
            ib.jd.setOnClickListener {
                start(ShopDetailsActivity::class.java, info.shop_id.toString())
            }
        }

        snapHelper = PagerSnapHelper()
        binding.mRecycler.layoutManager = layoutManager
        binding.mRecycler.adapter = pAdapter
        snapHelper.attachToRecyclerView(binding.mRecycler)
        binding.mRecycler.addOnScrollListener(
            object : RecyclerView.OnScrollListener() {

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        val view = snapHelper.findSnapView(layoutManager) ?: return
                        val childViewHolder = binding.mRecycler.getChildViewHolder(view)
                        val vh = childViewHolder as ListHolder
                        val ib = vh.binding as VideoItemBinding

                        videoPlayer = ib.jyVideo
                        ib.jyVideo.startVideo()

                        val view1 = snapHelper.findSnapView(layoutManager) ?: return
                        val position = binding.mRecycler.getChildAdapterPosition(view1)


                        if (position == videoList.size - 1 && !isLoading) {
                            isLoading = true
                            page++
                            getData()
                        }

                    }
                }
            })
    }


    private fun getData() {
        OKHttpUtils(activity, false)
            .SetApiUrl(LP_API.VIDEO_LIST)
            .SetKey("lng", "lat", "page", "category_id_one")
            .SetValue(
                SpUtils.getString("lng"),
                SpUtils.getString("lat"),
                page.toString(),
                category_id
            ).POST(this)

    }

    override fun callBack(event: Message?) {
        super.callBack(event)

        if (event!!.arg1 == LpKey.LOCATE_OK || event.arg1 == LpKey.LOCATE_ERR) {
            page = 1
            getData()
        }
    }


    override fun ok(jsonString: String?, httpTY: String?) {
        super.ok(jsonString, httpTY)
        isLoading = false
        val mode = Gson().fromJson(jsonString, VideoList::class.java)

        mode.data.let {
            if (it != null) {
                if (page == 1) {
                    videoList.clear()
                }
                videoList.addAll(it)
            } else {
                if (page == 1) {
                    "没有找到相关视频".show
                } else {
                    "到底了".show
                }
            }
        }


        pAdapter.notifyDataSetChanged()
        binding.small.Fin()


    }

    override fun error(e: String?, jsonString: String?, httpTY: String?) {
        super.error(e, jsonString, httpTY)
        isLoading = false
    }

    override fun getLay(): Int {
        return R.layout.video_fragment
    }

    override fun onResume() {
        super.onResume()
        Jzvd.goOnPlayOnResume()
        if (videoList.size == 0) {
            videoList.add(VideoListData(null))
        }
        videoPlayer?.let {
            if (it.state != Jzvd.STATE_PLAYING) {
                videoPlayer!!.startVideo()
            }
        }
    }

    override fun onPause() {
        super.onPause()
        Jzvd.goOnPlayOnPause()
    }
}
